package cn.net.xyan.facerecognition.service

import cn.net.xyan.facerecognition.dao.MaterialDao
import cn.net.xyan.facerecognition.dao.UserDao
import cn.net.xyan.facerecognition.entity.FaceMaterial
import cn.net.xyan.facerecognition.entity.User
import org.springframework.beans.factory.annotation.Autowired
import java.io.InputStream
import javax.imageio.ImageIO

interface FaceService{
    fun registerUser(username:String,password:String?):User
    fun addUserFace(username:String,data:InputStream)
    fun predict(data:InputStream):User?
}


class FaceServiceImpl:FaceService {

    @Autowired
    lateinit var userDao:UserDao

    @Autowired
    lateinit var materialDao:MaterialDao

    @Autowired
    lateinit var recognitionService:FaceRecognitionService

    fun findUser(username:String): User?{
        return userDao.findByUsername(username)
    }

    override fun registerUser(username: String, password: String?):User {
        var u = findUser(username)
        if (u != null) throw UnsupportedOperationException("user $username already exist!")

        u = User(username)
        u.password = password

        return userDao.saveAndFlush(u)
    }

    override fun addUserFace(username: String, data: InputStream) {

        val image = ImageIO.read(data)

        data.reset()

        var u = findUser(username)

        var m = FaceMaterial(u)

        m.imageData = data.readBytes()

        m = materialDao.saveAndFlush(m)

        recognitionService.update(image,m.label!!)
    }

    override fun predict(data: InputStream): User? {
        val image = ImageIO.read(data)

        val result =  recognitionService.predict(image)

        if (result.label == null) return null
        else
            return userDao.findByLabel(result.label)
    }
}